//
//  BKToolBar.swift
//  微博
//
//  Created by mac on 16/8/16.
//  Copyright © 2016年 xbk. All rights reserved.
//

import UIKit

enum BKToolBarType: Int {
    
    //图片
    case Picture = 0
    //@
    case Mention = 1
    //#
    case Trend = 2
    //表情
    case Emoticon = 3
    //加号
    case Add = 4
}

class BKToolBar: UIStackView {
    
    //点击按钮需要执行的闭包
    var didSelecteToolBarButtonClosure:((type:BKToolBarType)->())?
    
    //表情按钮
    var emotionButton:UIButton?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){
        
        axis = .Horizontal
        distribution = .FillEqually
    
        addChildButton("compose_toolbar_picture", type: .Picture)
        addChildButton("compose_mentionbutton_background", type: .Mention)
        addChildButton("compose_trendbutton_background", type: .Trend)
        emotionButton = addChildButton("compose_emoticonbutton_background", type: .Emoticon)
        addChildButton("compose_add_background", type: .Add)
    }
    
    //创建字按钮的通用方法
    private func addChildButton (imageName:String,type:BKToolBarType)->UIButton{
    
        let button = UIButton()
        
        button.tag = type.rawValue
        
        //设置图片
        button.setImage(UIImage(named: imageName), forState: .Normal)
        button.setImage(UIImage(named: "\(imageName)_highlighted"), forState: .Highlighted)
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: .Normal)
        
        //取消高亮效果
        button.adjustsImageWhenHighlighted = false
        
        button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
        
        addArrangedSubview(button)
        
        return button
    }
    
    
    @objc private func buttonAction(button:UIButton) {
    
        //通过原始值获取枚举
        let type = BKToolBarType(rawValue: button.tag)!
        
        //执行闭包,传送参数
        didSelecteToolBarButtonClosure?(type:type)
    }
    
    //根据外界传入的键盘类型,切换toolbar的图片
    func switchEmotionIcon(isEmotion:Bool){
        
        if isEmotion{
        
            emotionButton?.setImage(UIImage(named: "compose_keyboardbutton_background"), forState: .Normal)
            emotionButton?.setImage(UIImage(named:"compose_keyboardbutton_background_highlighted" ), forState: .Highlighted)
        }else {
        
        emotionButton?.setImage(UIImage(named: "compose_emoticonbutton_background"), forState: .Normal)
        emotionButton?.setImage(UIImage(named: "compose_emoticonbutton_background_highlighted"), forState: .Highlighted)
    }

    
    }
    
}
